package com.zklh.leetcode.top100.problem287;

/**
 * 解法2 判圈算法
 *
 * @Version 1.0
 * @Author tongnan
 * @Date 2023/12/26
 */
public class Solution2 {
    /**
     * 0 -> 1 -> 3 -> 2 -> 4 -> 2
     * @param nums 数组
     * @return 重复的数
     */
    public int findDuplicate(int[] nums) {
        int slow = 0, quick = 0;
        do {
            slow = nums[slow];
            quick = nums[nums[quick]];
        } while (slow != quick);
        slow = 0;
        while (slow != quick) {
            slow = nums[slow];
            quick = nums[quick];
        }
        return slow;
    }

    public static void main(String[] args) {
        Solution2 solution2 = new Solution2();
        int[] nums = {0, 1, 3, 2, 4, 2};
        System.out.println(solution2.findDuplicate(nums));
    }

}